package com.tanhua.dubbo.server.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //用来在Redis中查看关注用户
    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    /**
     * 发布小视频
     *
     * @param video
     * @return
     */
    @Override
    public String saveVideo(Video video) {

        try {
            //校验,传过来数据中有单个必填项
            if (!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getPicUrl(), video.getVideoUrl())) {
                return null;
            }

            //设置id
            video.setId(ObjectId.get());
            //设置自增长id，在Redis中，当前创建的id便为视屏的总数
            video.setVid(this.idService.createId(IdType.VIDEO));
            //发布时间
            //DateUtil.format(new Date(System.currentTimeMillis()), "HH-mm")
            video.setCreated(System.currentTimeMillis());
            //保存到MongoDB中
            this.mongoTemplate.save(video);
            return video.getId().toHexString();

        } catch (Exception e) {
            log.error("小视频保存失败！！！video = " + video);
        }
        return null;
    }

    /**
     * 分页查询视频列表，按照时间倒序排序
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        PageInfo<Video> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        //从Redis中查询推荐数据
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        //推荐系统中已经设定好的数据
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        List<Long> vids = new ArrayList<>();
        //用来获取推荐数据的总条数
        int recommendCount = 0;
        if (StrUtil.isNotEmpty(redisData)) {
            //手动分页查询数据
            List<String> vidList = StrUtil.split(redisData, ',');
            //计算分⻚
            //[0, 10]
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex = startEnd[0];
            int endIndex = Math.min(startEnd[1], vidList.size());

            for (int i = startIndex; i < endIndex; i++) {
                vids.add(Convert.toLong(vidList.get(i)));
            }
            recommendCount = vids.size();
        }
        if (CollUtil.isEmpty(vids)) {
            //没有推荐动态或者推荐动态已经查询完毕
            //计算之前推荐的页数
            int totalPage = PageUtil.totalPage(recommendCount, pageSize);
            PageRequest pageRequest = PageRequest.of(page - totalPage - 1,
                    pageSize, Sort.by(Sort.Order.desc("created")));
            Query query = new Query().with(pageRequest);
            List<Video> videoList = this.mongoTemplate.find(query, Video.class);
            pageInfo.setRecords(videoList);
            return pageInfo;
        }
        //根据vid查询对应的视频数据了

        Query query = Query.query(Criteria.where("vid").in(vids));
        List<Video> videoList = this.mongoTemplate.find(query, Video.class);
        pageInfo.setRecords(videoList);
        return pageInfo;
    }

    /**
     * 根据id查询视频对象
     *
     * @param publishId 当前video对象id
     * @return
     */
    @Override
    public Video queryVideoById(String publishId) {
        Video video = this.mongoTemplate.findById(new ObjectId(publishId), Video.class);
        return video;
    }

    /**
     * 关注用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    @Override
    public Boolean followUser(Long userId, Long followUserId) {

        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)){
            //有一项为空，返回
            return false;
        }

        try {
            //查看是否关注当前用户
            Boolean flag = this.isFollowUser(userId, followUserId);
            if (flag){
                //已经关注当前用户,不在完成当前操作
                return false;
            }

            String redisKey = this.getVideoFollowUserKey(userId);
            String hashKey = String.valueOf(followUserId);
            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());

            this.mongoTemplate.save(followUser);

            //减小MongoDB压力，将数据存入Redis中 状态1表示关注
            this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 取消关注
     *
     * @param userId 当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    @Override
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)){
            //有一项为空，返回
            return false;
        }

        try {
            Boolean flag = this.isFollowUser(userId, followUserId);
            if (!flag){
                //未关注
                return false;
            }
            //删除mongoDb中的关注
            Query query = Query.query(Criteria.where("userId").is(userId).and("followUserId").is(followUserId));
            DeleteResult result = this.mongoTemplate.remove(query, FollowUser.class);
            if (result.getDeletedCount() > 0){
                String redisKey = this.getVideoFollowUserKey(userId);
                String hashKey = String.valueOf(followUserId);
                //删除Redis中关注
                this.redisTemplate.opsForHash().delete(redisKey, hashKey);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 当前用户是否关注目标用户
     *
     * @param userId 当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    @Override
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = this.getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(followUserId);
        Boolean result = this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
        return result;
    }
    //获取key(在Redis中查询关注用户的大key)
    private String getVideoFollowUserKey(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }
}
